package com.training.admin.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.category.TrainingCategory;
import com.training.admin.entity.search.TrainerSearch;
import com.training.admin.entity.trainer.Trainer;
import com.training.admin.service.TrainerService;
import com.training.admin.service.TrainingCategoryService;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("/trainers")
@MenuSetting("menu-system-management")
public class TrainerController {
	private static final Logger logger = LoggerFactory.getLogger(TrainerController.class);
   
    @Autowired
    private TrainerService trainerService;
    @Autowired
    private TrainingCategoryService trainingCategoryService;
 
    	
	/**
     * 列表
     * @return
     */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-management")
    public ModelAndView list(Page page) {
		ModelAndView modelAndView = new ModelAndView("trainer/trainer-list");
		
		
		int totals = trainerService.count(Trainer.class);
		if(totals > 0) {
			List<Trainer> trainers = trainerService.listByPage(Trainer.class, page.with(totals));
			
			modelAndView.addObject("page", page);
			
	        modelAndView.addObject("trainers", trainers);
		}
		return modelAndView;
    }
    
	/**
	 * 查询
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-management")
	public ModelAndView search() {
		ModelAndView modelAndView = new ModelAndView("trainer/trainer-search");
		
		List <TrainingCategory> trainingCategoryList =trainingCategoryService.listAll(TrainingCategory.class);
		List<String> categories = new ArrayList<String>();
		for(int i=0;i<trainingCategoryList.size();i++){
			TrainingCategory trainingCategory = trainingCategoryList.get(i);
			if(trainingCategory.getName().contains("金讲台")){
				categories.add(trainingCategory.getName());
			}
		}
		modelAndView.addObject("categories",categories);
		return modelAndView;
	}
    /**
     * onSearch
     * 
     * @param trainerSearch
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-trainer-management")
    public ModelAndView onSearch(TrainerSearch trainerSearch, Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("trainer/trainer-list");
        int totals = trainerService.count(Trainer.class, trainerSearch.getFilter());
        if(totals > 0){
            List<Trainer> trainerList = trainerService.search(Trainer.class, trainerSearch, page.with(totals));
            modelAndView.addObject("trainers", trainerList);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        }
        return modelAndView;
        
    }
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-management")
	public ModelAndView edit(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("trainer/trainer-edit");
		Trainer trainer = trainerService.load(Trainer.class, id);
		modelAndView.addObject("trainer",trainer);
		List <TrainingCategory> trainingCategoryList =trainingCategoryService.listAll(TrainingCategory.class);
		List<String> categories = new ArrayList<String>();
		for(int i=0;i<trainingCategoryList.size();i++){
			TrainingCategory trainingCategory = trainingCategoryList.get(i);
			if(trainingCategory.getName().contains("金讲台")){
				categories.add(trainingCategory.getName());
			}
		}
		modelAndView.addObject("categories",categories);
		return modelAndView;
	}
	/**
	 * 修改提交
	 * @param trainer
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-trainer-management")
	public @ResponseBody HttpResult onEdit(@Preloading("trainerId") Trainer trainer) {
		HttpResult httpResult = new HttpResult();
		trainerService.update(trainer);
		httpResult.success().message("修改讲师信息成功");
		return httpResult;
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-management")
	public ModelAndView disable(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("trainer/trainer-delete");
		Trainer trainer = trainerService.load(Trainer.class, id);
		modelAndView.addObject("trainer",trainer);
		return modelAndView;
	}
	
	/**
	 * 删除提交
	 * @param trainer
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-trainer-management")
	public @ResponseBody HttpResult onDisable(@Preloading("trainerId") Trainer trainer) {
		HttpResult httpResult = new HttpResult();
		trainer.setDisabled(true);
		trainerService.update(trainer);
		httpResult.success().message("删除讲师信息成功");
		return httpResult;
	}
	
	/**
	 * 新增
	 * 
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-management")
	public ModelAndView create() {
		ModelAndView modelAndView = new ModelAndView("trainer/trainer-create");
		List <TrainingCategory> trainingCategoryList =trainingCategoryService.listAll(TrainingCategory.class);
		List<String> categories = new ArrayList<String>();
		for(int i=0;i<trainingCategoryList.size();i++){
			TrainingCategory trainingCategory = trainingCategoryList.get(i);
			if(trainingCategory.getName().contains("金讲台")){
				categories.add(trainingCategory.getName());
			}
		}
		modelAndView.addObject("categories",categories);
		return modelAndView;
	}

	/**
	 * 新增提交
	 * @param trainer
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-trainer-management")
	public  @ResponseBody HttpResult  onCreate(Trainer trainer) {
        HttpResult httpResult = new HttpResult();
        try {
        	
    		trainerService.save(trainer.create());
            httpResult.success().message("创建讲师成功！");
		} catch (Exception e) {
			httpResult.fail("500").message("创建讲师失败! " + e.getMessage());
			logger.error("#onCreate() - create trainer fail, exception is [{}]", e);
		}
        return httpResult;

	}
	
	/**
     * @param search
     * @return
     */
    @RequestMapping(value = "/select-search", params = "query", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult selectSearch(@RequestParam("query") String q) {

        HttpResult httpResult = new HttpResult();

        List<Map<String, String>> maps = trainerService.getTrainerIdAndName(q);
        httpResult.success().data("trainers", maps);

        return httpResult;
    }
    
    /**
     * 
     * @param userName
     * @return
     */
    @RequestMapping(value = "select",params = "query", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult selectSearchs(@RequestParam("query") String userName) {
    	
    	HttpResult httpResult = new HttpResult();
    	List<Map<String,String>> idmUser = trainerService.getIdmUser(userName);
    	httpResult.success().data("idmUser", idmUser);
    	return httpResult;
    }
	
	/*
	 * @RequestMapping(value = "select", method = RequestMethod.GET, produces =
	 * MediaType.APPLICATION_JSON_UTF8_VALUE)
	 * 
	 * @ResponseBody public HttpResult selectSearchs(@RequestParam("userName")
	 * String userName) {
	 * 
	 * HttpResult httpResult = new HttpResult();
	 * 
	 * try { List<IdmUser> idmUsers = trainerService.loadByUserName(userName);
	 * Map<String, String> map = new HashMap<String, String>();
	 * map.compute("userName", remappingFunction) } catch (Exception e) { // TODO:
	 * handle exception }
	 * 
	 * return httpResult; }
	 */
}
